<template>
  <div class="phrase-list">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>销售合同管理</h2>
      <p>销售合同信息查询与管理</p>
    </div>

    <!-- 搜索区域 -->
    <el-card class="search-card" shadow="never">
      <el-form :model="searchForm" :inline="true" class="search-form">
        <el-form-item label="合同名称">
          <el-input
            v-model="searchForm.ContractName"
            placeholder="请输入合同名称"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="客户">
          <el-select
            v-model="searchForm.CustomerId"
            placeholder="请选择客户"
            clearable
            style="width: 200px"
          >
            <el-option
              v-for="customer in customerOptions"
              :key="customer.id"
              :label="customer.customerName"
              :value="customer.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="审核状态">
          <el-select
            v-model="searchForm.Review"
            placeholder="请选择审核状态"
            clearable
            style="width: 150px"
          >
            <el-option label="已审核" :value="1" />
            <el-option label="未审核" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch" :loading="loading">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作按钮区域 -->
    <el-card class="action-card" shadow="never">
      <div class="action-buttons">
        <el-button type="primary" @click="handleAdd">
          <el-icon><Plus /></el-icon>
          新增合同
        </el-button>
        <el-button type="success" @click="handleExport" :loading="exportLoading">
          <el-icon><Download /></el-icon>
          导出数据
        </el-button>
      </div>
    </el-card>

    <!-- 数据表格 -->
    <el-card class="table-card" shadow="never">
      <el-table :data="tableData" v-loading="loading" stripe border style="width: 100%">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="contractName" label="合同名称" width="200">
          <template #default="{ row }">
            <el-link type="primary" @click="handleDetail(row)">
              {{ row.contractName }}
            </el-link>
          </template>
        </el-table-column>
        <el-table-column prop="contractCode" label="合同编号" width="120" />
        <el-table-column prop="customerName" label="客户名称" width="180" />
        <el-table-column prop="customerCode" label="客户编码" width="120" />
        <el-table-column prop="customerType" label="客户类型" width="100">
          <template #default="{ row }">
            <el-tag :type="row.customerType === '企业' ? 'primary' : 'success'">
              {{ row.customerType }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="contractPrice" label="合同价格" width="120">
          <template #default="{ row }">
            ¥{{ row.contractPrice }}
          </template>
        </el-table-column>
        <el-table-column prop="userPeople" label="联系人" width="120" />
        <el-table-column prop="phone" label="联系电话" width="140" />
        <el-table-column prop="review" label="审核状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.review === 1 ? 'success' : 'info'">
              {{ row.review === 1 ? '已审核' : '未审核' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="state" label="状态" width="80">
          <template #default="{ row }">
            <el-tag :type="row.state === 1 ? 'success' : 'danger'">
              {{ row.state === 1 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180">
          <template #default="{ row }">
            {{ formatDateTime(row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="updateTime" label="更新时间" width="180">
          <template #default="{ row }">
            {{ formatDateTime(row.updateTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="320" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleDetail(row)">
              <el-icon><View /></el-icon>
              详情
            </el-button>
            <el-button type="success" size="small" @click="handleEdit(row)">
              <el-icon><Edit /></el-icon>
              编辑
            </el-button>
            <el-button 
              v-if="row.review === 0" 
              type="warning" 
              size="small" 
              @click="handleSingleReview(row)"
              :loading="row.reviewLoading"
            >
              审核
            </el-button>
            <el-button 
              v-if="row.review === 1" 
              type="info" 
              size="small" 
              @click="handleCancelReview(row)"
              :loading="row.reviewLoading"
            >
              取消审核
            </el-button>
            <el-button type="danger" size="small" @click="handleDelete(row)">
              <el-icon><Delete /></el-icon>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.pageindex"
          v-model:page-size="pagination.pagesize"
          :page-sizes="[6, 10, 20, 50, 100]"
          :total="pagination.totalCount"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑合同对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑销售合同' : '新增销售合同'"
      width="600px"
      :close-on-click-modal="false"
      @close="handleDialogClose"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="120px"
        class="phrase-form"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="合同名称" prop="contractName">
              <el-input
                v-model="formData.contractName"
                placeholder="请输入合同名称"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="合同编号" prop="contractCode">
              <el-input
                v-model="formData.contractCode"
                placeholder="系统自动生成"
                readonly
                disabled
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="客户" prop="customerId">
              <el-input
                v-model="selectedCustomerName"
                placeholder="请选择客户"
                readonly
                @click="handleCustomerSelect"
                style="width: 100%"
              >
                <template #suffix>
                  <el-icon class="el-input__icon"><Search /></el-icon>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="合同价格" prop="contractPrice">
              <el-input-number
                v-model="formData.contractPrice"
                placeholder="请输入合同价格"
                :min="0"
                :precision="2"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="产品ID" prop="productId">
              <el-input-number
                v-model="formData.productId"
                placeholder="请输入产品ID"
                :min="1"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="审核状态" prop="review">
              <el-radio-group v-model="formData.review">
                <el-radio :label="1">已审核</el-radio>
                <el-radio :label="0">未审核</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="创建时间" prop="createTime">
              <el-date-picker
                v-model="formData.createTime"
                type="datetime"
                placeholder="请选择创建时间"
                style="width: 100%"
                format="YYYY-MM-DD HH:mm:ss"
                value-format="YYYY-MM-DDTHH:mm:ss.sssZ"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="更新时间" prop="updateTime">
              <el-date-picker
                v-model="formData.updateTime"
                type="datetime"
                placeholder="请选择更新时间"
                style="width: 100%"
                format="YYYY-MM-DD HH:mm:ss"
                value-format="YYYY-MM-DDTHH:mm:ss.sssZ"
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item label="备注" prop="desc">
          <el-input
            v-model="formData.desc"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleDialogClose">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
            {{ isEdit ? '保存' : '新增' }}
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 详情对话框 -->
    <el-dialog
      v-model="detailVisible"
      title="合同详情"
      width="800px"
      :before-close="handleDetailClose"
    >
      <div v-if="currentDetail" class="detail-content">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="合同名称">
            <el-tag type="primary">{{ currentDetail.contractName }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="合同编号">
            <el-tag type="info">{{ currentDetail.contractCode }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="合同价格">
            <span class="amount-text">¥{{ currentDetail.contractPrice }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="客户名称">
            {{ currentDetail.customerName }}
          </el-descriptions-item>
          <el-descriptions-item label="客户编码">
            <el-tag type="success">{{ currentDetail.customerCode }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="客户类型">
            <el-tag :type="currentDetail.customerType === '企业' ? 'primary' : 'success'">
              {{ currentDetail.customerType }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="联系人">
            {{ currentDetail.userPeople }}
          </el-descriptions-item>
          <el-descriptions-item label="联系电话">
            {{ currentDetail.phone }}
          </el-descriptions-item>
          <el-descriptions-item label="审核状态">
            <el-tag :type="currentDetail.review === 1 ? 'success' : 'info'">
              {{ currentDetail.review === 1 ? '已审核' : '未审核' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="合同状态">
            <el-tag :type="currentDetail.state === 1 ? 'success' : 'danger'">
              {{ currentDetail.state === 1 ? '启用' : '禁用' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="创建时间">
            {{ formatDateTime(currentDetail.createTime) }}
          </el-descriptions-item>
          <el-descriptions-item label="更新时间">
            {{ formatDateTime(currentDetail.updateTime) }}
          </el-descriptions-item>
          <el-descriptions-item label="备注信息" :span="2">
            {{ currentDetail.desc || '无' }}
          </el-descriptions-item>
        </el-descriptions>
      </div>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleDetailClose">关闭</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 客户选择对话框 -->
    <el-dialog
      v-model="customerSelectVisible"
      title="选择客户"
      width="800px"
      :close-on-click-modal="false"
      @close="handleCustomerSelectClose"
    >
      <!-- 搜索区域 -->
      <el-form :model="customerSearchForm" :inline="true" class="customer-search-form">
        <el-form-item label="客户编号/名称">
          <el-input
            v-model="customerSearchForm.customerName"
            placeholder="请输入客户编号/名称"
            clearable
            style="width: 250px"
          />
        </el-form-item>
        <el-form-item label="客户类型">
          <el-select
            v-model="customerSearchForm.customerType"
            placeholder="请选择客户类型"
            clearable
            style="width: 150px"
          >
            <el-option label="全部" value="" />
            <el-option label="企业" value="企业" />
            <el-option label="个人" value="个人" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button @click="handleCustomerSearchReset">重置</el-button>
          <el-button type="primary" @click="handleCustomerSearch">查询</el-button>
        </el-form-item>
      </el-form>

      <!-- 客户列表表格 -->
      <el-table
        :data="customerTableData"
        v-loading="customerLoading"
        stripe
        border
        style="width: 100%"
        @row-click="handleCustomerRowClick"
      >
        <el-table-column width="60">
          <template #default="{ row }">
            <el-radio
              v-model="selectedCustomerId"
              :label="row.id"
              @change="() => handleCustomerRadioChange(row)"
            >
              &nbsp;
            </el-radio>
          </template>
        </el-table-column>
        <el-table-column prop="customerCode" label="客户编码" width="120" />
        <el-table-column prop="customerName" label="客户名称" width="180" />
        <el-table-column prop="customerType" label="客户类型" width="100">
          <template #default="{ row }">
            <el-tag :type="row.customerType === '企业' ? 'primary' : 'success'">
              {{ row.customerType }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="userPeople" label="联系人" width="120" />
        <el-table-column prop="phone" label="联系电话" width="140" />
        <el-table-column prop="state" label="状态" width="80">
          <template #default="{ row }">
            <el-tag :type="row.state === 1 ? 'success' : 'danger'">
              {{ row.state === 1 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        v-model:current-page="customerPagination.pageIndex"
        v-model:page-size="customerPagination.pageSize"
        :page-sizes="[5, 10, 20, 50]"
        :total="customerPagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleCustomerSizeChange"
        @current-change="handleCustomerCurrentChange"
        style="margin-top: 20px; text-align: right"
      />

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleCustomerSelectClose">取消</el-button>
          <el-button type="primary" @click="handleCustomerConfirm">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, Plus, Download, Edit, View, Delete } from '@element-plus/icons-vue'
import { getReadClient, getWriteClient } from '@/Urls/AxiosHelper'

// 使用正确的客户端
const r3 = getReadClient(0)
const w8 = getWriteClient(0)

// 接口类型定义
interface Phrase {
  id: number
  contractName: string
  contractCode: string
  updateTime: string
  customerId: number
  contractPrice: number
  createTime: string
  review: number
  desc: string
  productId: number
  isDelete: boolean
  customerCode: string
  customerName: string
  customerType: string
  userPeople: string
  state: number
  phone: string
  reviewLoading?: boolean // 审核按钮加载状态
}

interface Customer {
  id: number
  customerName: string
  customerCode: string
  customerType: string
  userPeople: string
  phone: string
  state: number
}

interface ApiResponse {
  data: {
    totalCount: number
    totalPage: number
    data: Phrase[]
  }
  code: number
  message: string
}

// 响应式数据
const loading = ref(false)
const tableData = ref<Phrase[]>([])
const exportLoading = ref(false)
const customerOptions = ref<Customer[]>([])

// 客户选择对话框相关
const customerSelectVisible = ref(false)
const customerTableData = ref<Customer[]>([])
const customerLoading = ref(false)
const selectedCustomerId = ref<number | null>(null)
const selectedCustomerName = ref('')
const customerSearchForm = reactive({
  customerName: '',
  customerType: ''
})
const customerPagination = reactive({
  pageIndex: 1,
  pageSize: 10,
  total: 0
})

// 详情相关
const detailVisible = ref(false)
const currentDetail = ref<Phrase | null>(null)

// 新增/编辑对话框相关
const dialogVisible = ref(false)
const submitLoading = ref(false)
const formRef = ref()
const isEdit = ref(false)
const currentEditId = ref<number | null>(null)

// 搜索表单
const searchForm = reactive({
  ContractName: '',
  CustomerId: null as number | null,
  Review: null as number | null
})

// 分页数据
const pagination = reactive({
  pageindex: 1,
  pagesize: 6,
  totalCount: 0,
  totalPage: 0
})

// 表单数据
const formData = reactive({
  contractName: '',
  contractCode: '',
  customerId: null as number | null,
  contractPrice: 0,
  productId: null as number | null,
  createTime: '',
  updateTime: '',
  review: 0,
  desc: ''
})

// 表单验证规则
const formRules = {
  contractName: [
    { required: true, message: '请输入合同名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  customerId: [
    { required: true, message: '请选择客户', trigger: 'change' }
  ],
  contractPrice: [
    { required: true, message: '请输入合同价格', trigger: 'blur' },
    { type: 'number', min: 0, message: '合同价格不能小于0', trigger: 'blur' }
  ],
  productId: [
    { required: true, message: '请输入产品ID', trigger: 'blur' }
  ],
  createTime: [
    { required: true, message: '请选择创建时间', trigger: 'change' }
  ],
  updateTime: [
    { required: true, message: '请选择更新时间', trigger: 'change' }
  ]
}

// 获取销售合同列表数据
const fetchPhraseList = async () => {
  try {
    loading.value = true
    
    const params = {
      pageindex: pagination.pageindex,
      pagesize: pagination.pagesize,
      ContractName: searchForm.ContractName || undefined,
      CustomerId: searchForm.CustomerId || undefined,
      Review: searchForm.Review !== null ? searchForm.Review : undefined
    }

    // 移除空值参数
    Object.keys(params).forEach(key => {
      const paramKey = key as keyof typeof params
      if (params[paramKey] === undefined || params[paramKey] === '') {
        delete params[paramKey]
      }
    })

    console.log('API请求参数:', params)
    console.log('使用的客户端:', r3.defaults.baseURL)
    
    const response = await r3.get<ApiResponse>('/sellreadapi/api/Phrase/Phraselist', { params })
    
    if (response.data.code === 200) {
      tableData.value = response.data.data.data.map((item: Phrase) => ({
        ...item,
        reviewLoading: false // 初始化审核按钮加载状态
      }))
      pagination.totalCount = response.data.data.totalCount
      pagination.totalPage = response.data.data.totalPage
      console.log('获取到的数据:', tableData.value)
    } else {
      ElMessage.error(response.data.message || '获取销售合同列表失败')
    }
  } catch (error: any) {
    console.error('获取销售合同列表失败:', error)
    ElMessage.error(`网络请求失败: ${error.message}`)
  } finally {
    loading.value = false
  }
}

// 获取客户列表
const fetchCustomerList = async () => {
  try {
    const response = await r3.get<ApiResponse>('/sellreadapi/api/Customer/Customerlist', {
      params: {
        pageindex: 1,
        pagesize: 1000
      }
    })
    
    if (response.data.code === 200) {
      customerOptions.value = response.data.data.data
      console.log('客户列表加载成功:', customerOptions.value.length, '条')
      console.log('客户列表数据:', customerOptions.value)
    }
  } catch (error: any) {
    console.error('获取客户列表失败:', error)
    // 使用模拟数据
    customerOptions.value = [
      { id: 1, customerName: '螺蛳粉爱好者店铺', customerCode: 'C001', customerType: '企业', userPeople: '张三', phone: '13800138001', state: 1 },
      { id: 2, customerName: '销售合同01', customerCode: 'Cus002', customerType: '个人', userPeople: '李四', phone: '13800138002', state: 1 },
      { id: 3, customerName: '测试客户', customerCode: 'C003', customerType: '企业', userPeople: '王五', phone: '13800138003', state: 1 }
    ]
  }
}

// 搜索处理
const handleSearch = () => {
  pagination.pageindex = 1 // 重置到第一页
  fetchPhraseList()
}

// 重置搜索
const handleReset = () => {
  searchForm.ContractName = ''
  searchForm.CustomerId = null
  searchForm.Review = null
  pagination.pageindex = 1
  fetchPhraseList()
}

// 分页大小改变
const handleSizeChange = (val: number) => {
  pagination.pagesize = val
  pagination.pageindex = 1
  fetchPhraseList()
}

// 当前页改变
const handleCurrentChange = (val: number) => {
  pagination.pageindex = val
  fetchPhraseList()
}

// 查看详情
const handleDetail = (row: Phrase) => {
  currentDetail.value = row
  detailVisible.value = true
}

// 关闭详情对话框
const handleDetailClose = () => {
  detailVisible.value = false
  currentDetail.value = null
}

// 生成合同编号
const generateContractCode = () => {
  const now = new Date()
  const year = now.getFullYear()
  const month = String(now.getMonth() + 1).padStart(2, '0')
  const day = String(now.getDate()).padStart(2, '0')
  const hours = String(now.getHours()).padStart(2, '0')
  const minutes = String(now.getMinutes()).padStart(2, '0')
  const seconds = String(now.getSeconds()).padStart(2, '0')
  
  return `C${year}${month}${day}${hours}${minutes}${seconds}`
}

// 格式化日期为日期选择器需要的格式
const formatDateForPicker = (dateString: string) => {
  if (!dateString) return ''
  
  try {
    const date = new Date(dateString)
    // 检查日期是否有效
    if (isNaN(date.getTime())) {
      console.warn('无效的日期格式:', dateString)
      return ''
    }
    // 转换为ISO格式，匹配value-format="YYYY-MM-DDTHH:mm:ss.sssZ"
    return date.toISOString()
  } catch (error) {
    console.error('日期格式转换失败:', error, '原始值:', dateString)
    return ''
  }
}

// 新增合同
const handleAdd = () => {
  isEdit.value = false
  currentEditId.value = null
  resetForm()
  // 自动生成合同编号
  formData.contractCode = generateContractCode()
  // 设置默认时间为当前时间 - 使用API图片中的格式
  const now = new Date()
  const isoString = now.toISOString()
  // 根据API图片，日期格式应该是 "2025-09-20T01:30:14.6897" 这样的格式
  formData.createTime = isoString
  formData.updateTime = isoString
  console.log('生成的合同编号:', formData.contractCode)
  console.log('设置的创建时间:', formData.createTime)
  console.log('设置的更新时间:', formData.updateTime)
  dialogVisible.value = true
}

// 编辑合同
const handleEdit = async (row: Phrase) => {
  isEdit.value = true
  currentEditId.value = row.id
  dialogVisible.value = true
  
  // 填充表单数据
  formData.contractName = row.contractName
  formData.contractCode = row.contractCode
  formData.customerId = row.customerId
  formData.contractPrice = row.contractPrice
  formData.productId = row.productId
  formData.review = row.review
  formData.desc = row.desc || ''
  
  // 确保客户列表已加载
  if (customerOptions.value.length === 0) {
    console.log('客户列表为空，重新加载...')
    await fetchCustomerList()
  }
  
  // 设置客户名称显示
  console.log('编辑时的行数据:', row)
  console.log('客户ID:', row.customerId)
  console.log('客户名称:', row.customerName)
  console.log('当前客户选项:', customerOptions.value)
  
  // 强制从客户列表中查找客户名称
  const customer = customerOptions.value.find(c => c.id === row.customerId)
  if (customer) {
    selectedCustomerName.value = customer.customerName
    console.log('从客户列表中找到客户名称:', customer.customerName)
  } else {
    // 如果客户列表中没有，尝试使用行数据中的客户名称
    selectedCustomerName.value = row.customerName || ''
    console.log('使用行数据中的客户名称:', row.customerName)
  }
  
  console.log('最终设置的客户名称:', selectedCustomerName.value)
  
  // 处理日期格式，确保与日期选择器的value-format匹配
  formData.createTime = formatDateForPicker(row.createTime)
  formData.updateTime = formatDateForPicker(row.updateTime)
  
  // 清除表单验证
  if (formRef.value) {
    formRef.value.clearValidate()
  }
}

// 重置表单
const resetForm = () => {
  formData.contractName = ''
  formData.contractCode = ''
  formData.customerId = null
  formData.contractPrice = 0
  formData.productId = null
  formData.createTime = ''
  formData.updateTime = ''
  formData.review = 0
  formData.desc = ''
  // 清空客户名称显示
  selectedCustomerName.value = ''
  // 清除表单验证
  if (formRef.value) {
    formRef.value.clearValidate()
  }
}

// 关闭对话框
const handleDialogClose = () => {
  dialogVisible.value = false
  isEdit.value = false
  currentEditId.value = null
  resetForm()
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    // 验证表单
    await formRef.value.validate()
    
    submitLoading.value = true
    
    // 准备提交数据 - 根据API图片调整字段格式
    const submitData: any = {
      ContractName: formData.contractName,
      ContractCode: formData.contractCode,
      CustomerId: formData.customerId,
      ContractPrice: formData.contractPrice,
      ProductId: formData.productId,
      CreateTime: formData.createTime,
      UpdateTime: formData.updateTime,
      Review: formData.review,
      Desc: formData.desc || '无'
    }
    
    // 确保必填字段不为空
    if (!submitData.ContractName) {
      ElMessage.error('请输入合同名称')
      submitLoading.value = false
      return
    }
    if (!submitData.CustomerId) {
      ElMessage.error('请选择客户')
      submitLoading.value = false
      return
    }
    if (!submitData.ContractPrice || submitData.ContractPrice <= 0) {
      ElMessage.error('请输入有效的合同价格')
      submitLoading.value = false
      return
    }
    if (!submitData.ProductId) {
      ElMessage.error('请输入产品ID')
      submitLoading.value = false
      return
    }
    
    // 如果是编辑模式，添加ID
    if (isEdit.value && currentEditId.value) {
      submitData.id = currentEditId.value
    }
    
    console.log('提交数据:', submitData)
    console.log('是否为编辑模式:', isEdit.value)
    console.log('使用的API端点:', isEdit.value ? '/sellwriteapi/api/Phrases/PhrasesUpdate' : '/sellwriteapi/api/Phrases/PhrasesAdd')
    
    let response
    if (isEdit.value) {
      // 调用编辑接口
      console.log('调用编辑接口...')
      response = await w8.post('/sellwriteapi/api/Phrases/PhrasesUpdate', submitData)
    } else {
      // 调用新增接口
      console.log('调用新增接口...')
      response = await w8.post('/sellwriteapi/api/Phrases/PhrasesAdd', submitData)
    }
    
    console.log('API响应状态:', response.status)
    console.log('API响应数据:', response.data)
    
    // 检查API响应 - 根据控制台输出，API返回的是 {Data: 1, Code: 200, Message: '销售合同添加成功'}
    // 注意：API返回的字段是大写的 Code，不是小写的 code
    if (response.data && response.data.Code === 200) {
      ElMessage.success(isEdit.value ? '销售合同修改成功' : '销售合同新增成功')
      dialogVisible.value = false
      resetForm()
      // 刷新列表
      fetchPhraseList()
    } else {
      ElMessage.error(response.data?.Message || (isEdit.value ? '修改失败' : '新增失败'))
    }
  } catch (error: any) {
    console.error(isEdit.value ? '修改失败:' : '新增失败:', error)
    
    if (error.response) {
      console.error('响应状态:', error.response.status)
      console.error('响应数据:', error.response.data)
      ElMessage.error(`服务器错误 (${error.response.status}): ${error.response.data?.message || '请检查后端服务是否正常运行'}`)
    } else if (error.request) {
      console.error('请求失败:', error.request)
      ElMessage.error('网络连接失败，请检查后端服务是否启动')
    } else {
      console.error('请求配置错误:', error.message)
      ElMessage.error(`请求配置错误: ${error.message}`)
    }
  } finally {
    submitLoading.value = false
  }
}

// 删除合同
const handleDelete = async (row: Phrase) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除合同 "${row.contractName}" 吗？`,
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 调用删除API
    console.log('调用删除接口，ID:', row.id)
    const response = await r3.get('/sellwriteapi/api/Phrases/PhrasesDel', {
      params: { Id: row.id }
    })
    
    console.log('删除API响应:', response.data)
    
    // 检查API响应 - 根据API文档，成功响应格式为 {Data: 1, Code: 200, Message: "销售合同删除成功"}
    if (response.data && response.data.Code === 200) {
      ElMessage.success('销售合同删除成功')
      // 刷新列表
      fetchPhraseList()
    } else {
      ElMessage.error(response.data?.Message || '删除失败')
    }
  } catch (error: any) {
    if (error.message === 'cancel') {
      ElMessage.info('已取消删除')
    } else {
      console.error('删除合同失败:', error)
      if (error.response) {
        ElMessage.error(`删除失败: ${error.response.data?.Message || '服务器错误'}`)
      } else if (error.request) {
        ElMessage.error('删除失败: 网络连接错误')
      } else {
        ElMessage.error(`删除失败: ${error.message}`)
      }
    }
  }
}

// 导出数据
const handleExport = async () => {
  try {
    exportLoading.value = true
    
    // 获取所有销售合同数据（不分页）
    const params = {
      pageindex: 1,
      pagesize: 10000,
      ContractName: searchForm.ContractName || undefined,
      CustomerId: searchForm.CustomerId || undefined,
      Review: searchForm.Review !== null ? searchForm.Review : undefined
    }

    // 移除空值参数
    Object.keys(params).forEach(key => {
      const paramKey = key as keyof typeof params
      if (params[paramKey] === undefined || params[paramKey] === '') {
        delete params[paramKey]
      }
    })

    const response = await r3.get<ApiResponse>('/sellreadapi/api/Phrase/Phraselist', { params })
    
    if (response.data.code === 200) {
      const exportData = response.data.data.data
      
      if (exportData.length === 0) {
        ElMessage.warning('没有数据可导出')
        return
      }
      
      // 准备导出数据
      const excelData = exportData.map((item, index) => ({
        '序号': index + 1,
        '合同名称': item.contractName,
        '合同编号': item.contractCode,
        '客户名称': item.customerName,
        '客户编码': item.customerCode,
        '客户类型': item.customerType,
        '合同价格': `¥${item.contractPrice}`,
        '联系人': item.userPeople,
        '联系电话': item.phone,
        '审核状态': item.review === 1 ? '已审核' : '未审核',
        '合同状态': item.state === 1 ? '启用' : '禁用',
        '备注': item.desc,
        '创建时间': formatDateTime(item.createTime),
        '更新时间': formatDateTime(item.updateTime)
      }))
      
      // 生成Excel文件
      await exportToExcel(excelData, '销售合同列表')
      
      ElMessage.success(`导出成功，共导出 ${exportData.length} 条数据`)
    } else {
      ElMessage.error(response.data.message || '导出失败')
    }
  } catch (error: any) {
    console.error('导出失败:', error)
    ElMessage.error('导出失败，请重试')
  } finally {
    exportLoading.value = false
  }
}

// 导出到Excel
const exportToExcel = async (data: any[], filename: string) => {
  try {
    // 动态导入xlsx库
    const XLSX = await import('xlsx')
    
    // 创建工作簿
    const wb = XLSX.utils.book_new()
    
    // 创建工作表
    const ws = XLSX.utils.json_to_sheet(data)
    
    // 设置列宽
    const colWidths = [
      { wch: 8 },   // 序号
      { wch: 20 },  // 合同名称
      { wch: 15 },  // 合同编号
      { wch: 20 },  // 客户名称
      { wch: 15 },  // 客户编码
      { wch: 12 },  // 客户类型
      { wch: 12 },  // 合同价格
      { wch: 15 },  // 联系人
      { wch: 15 },  // 联系电话
      { wch: 12 },  // 审核状态
      { wch: 12 },  // 合同状态
      { wch: 30 },  // 备注
      { wch: 20 },  // 创建时间
      { wch: 20 }   // 更新时间
    ]
    ws['!cols'] = colWidths
    
    // 设置表头样式
    const headerStyle = {
      font: { bold: true, color: { rgb: "FFFFFF" } },
      fill: { fgColor: { rgb: "4472C4" } },
      alignment: { horizontal: "center", vertical: "center" }
    }
    
    // 应用表头样式
    const range = XLSX.utils.decode_range(ws['!ref'] || 'A1')
    for (let col = range.s.c; col <= range.e.c; col++) {
      const cellAddress = XLSX.utils.encode_cell({ r: 0, c: col })
      if (!ws[cellAddress]) ws[cellAddress] = { v: '' }
      ws[cellAddress].s = headerStyle
    }
    
    // 添加工作表到工作簿
    XLSX.utils.book_append_sheet(wb, ws, '销售合同列表')
    
    // 生成文件名（包含时间戳）
    const now = new Date()
    const timestamp = now.toISOString().slice(0, 19).replace(/[-:T]/g, '')
    const fileName = `${filename}_${timestamp}.xlsx`
    
    // 导出文件
    XLSX.writeFile(wb, fileName)
  } catch (error) {
    console.error('Excel导出失败:', error)
    throw new Error('Excel文件生成失败')
  }
}


// 格式化日期时间
const formatDateTime = (dateTime: string) => {
  if (!dateTime) return ''
  const date = new Date(dateTime)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}

// 客户选择相关函数
const handleCustomerSelect = () => {
  console.log('打开客户选择对话框')
  customerSelectVisible.value = true
  selectedCustomerId.value = null
  selectedCustomerName.value = ''
  // 重置搜索表单
  customerSearchForm.customerName = ''
  customerSearchForm.customerType = ''
  // 重置分页
  customerPagination.pageIndex = 1
  customerPagination.pageSize = 10
  // 获取客户列表
  fetchCustomerTableData()
}

const fetchCustomerTableData = async () => {
  try {
    customerLoading.value = true
    console.log('获取客户列表数据...')
    console.log('当前分页参数:', customerPagination)
    console.log('搜索条件:', customerSearchForm)
    
    const params = new URLSearchParams()
    params.append('pageindex', customerPagination.pageIndex.toString())
    params.append('pagesize', customerPagination.pageSize.toString())
    
    if (customerSearchForm.customerName) {
      params.append('CustomerName', customerSearchForm.customerName)
    }
    if (customerSearchForm.customerType) {
      params.append('CustomerType', customerSearchForm.customerType)
    }
    
    console.log('API请求URL:', `/sellreadapi/api/Customer/Customerlist?${params.toString()}`)
    const response = await r3.get(`/sellreadapi/api/Customer/Customerlist?${params.toString()}`)
    console.log('客户列表API响应:', response.data)
    
    // 检查API响应 - 根据API图片，数据结构是 response.data.data.data
    if (response.data && response.data.data) {
      const data = response.data.data.data || []
      customerTableData.value = data
      customerPagination.total = response.data.data.totalCount || 0
      console.log('客户列表数据加载成功:', data.length, '条')
      console.log('客户数据:', data)
      console.log('总数量:', response.data.data.totalCount)
    } else {
      console.warn('API响应异常，使用模拟数据')
      loadMockCustomerData()
    }
  } catch (error) {
    console.error('获取客户列表失败:', error)
    console.warn('API调用失败，使用模拟数据')
    loadMockCustomerData()
  } finally {
    customerLoading.value = false
  }
}

// 加载模拟客户数据
const loadMockCustomerData = () => {
  console.log('加载模拟客户数据...')
  customerTableData.value = [
    { id: 1, customerName: '王小雨', customerCode: 'C001', customerType: '企业', userPeople: '张三', phone: '13800138001', state: 1 },
    { id: 2, customerName: '孙苗苗', customerCode: 'C002', customerType: '个人', userPeople: '李四', phone: '13800138002', state: 1 },
    { id: 3, customerName: '测试客户', customerCode: 'C003', customerType: '企业', userPeople: '王五', phone: '13800138003', state: 1 },
    { id: 4, customerName: '示例企业', customerCode: 'C004', customerType: '企业', userPeople: '赵六', phone: '13800138004', state: 1 },
    { id: 5, customerName: '个人客户', customerCode: 'C005', customerType: '个人', userPeople: '钱七', phone: '13800138005', state: 1 }
  ]
  customerPagination.total = 5
  console.log('模拟客户数据加载完成:', customerTableData.value.length, '条')
}

const handleCustomerSearch = () => {
  console.log('执行客户搜索...')
  customerPagination.pageIndex = 1
  fetchCustomerTableData()
}

const handleCustomerSearchReset = () => {
  console.log('重置客户搜索...')
  customerSearchForm.customerName = ''
  customerSearchForm.customerType = ''
  customerPagination.pageIndex = 1
  fetchCustomerTableData()
}

const handleCustomerSizeChange = (val: number) => {
  customerPagination.pageSize = val
  customerPagination.pageIndex = 1
  fetchCustomerTableData()
}

const handleCustomerCurrentChange = (val: number) => {
  customerPagination.pageIndex = val
  fetchCustomerTableData()
}

const handleCustomerRowClick = (row: Customer) => {
  console.log('客户行点击选择前:', selectedCustomerName.value)
  selectedCustomerId.value = row.id
  selectedCustomerName.value = row.customerName
  // 立即更新表单数据
  formData.customerId = row.id
  console.log('客户行点击选择后:', selectedCustomerName.value, 'formData.customerId:', formData.customerId)
}

const handleCustomerRadioChange = (row: Customer) => {
  console.log('客户单选按钮选择前:', selectedCustomerName.value)
  selectedCustomerId.value = row.id
  selectedCustomerName.value = row.customerName
  // 立即更新表单数据
  formData.customerId = row.id
  console.log('客户单选按钮选择后:', selectedCustomerName.value, 'formData.customerId:', formData.customerId)
}

const handleCustomerConfirm = () => {
  if (selectedCustomerId.value) {
    // 数据已经在选择时更新了，直接关闭对话框
    customerSelectVisible.value = false
    console.log('客户选择确认:', selectedCustomerId.value, selectedCustomerName.value)
  } else {
    ElMessage.warning('请选择一个客户')
  }
}

const handleCustomerSelectClose = () => {
  customerSelectVisible.value = false
  // 只有在没有选择客户时才清空数据
  if (!selectedCustomerId.value) {
    selectedCustomerName.value = ''
  }
}

// 单个审核功能
const handleSingleReview = async (row: Phrase) => {
  try {
    await ElMessageBox.confirm(
      `确定要审核销售合同 "${row.contractName}" 吗？`,
      '审核确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 设置行级加载状态
    row.reviewLoading = true
    
    console.log('发送审核请求:', { Id: row.id, ReviewStatus: 1 })
    console.log('使用的客户端:', w8.defaults.baseURL)
    
    const response = await w8.post('/sellwriteapi/api/Phrases/PhrasesUpdateReviewStatus', {
      Id: row.id,
      ReviewStatus: 1
    })
    
    console.log('审核响应:', response.data)
    console.log('响应状态:', response.status)
    
    // 检查响应
    const responseData = response.data
    const httpStatus = response.status
    
    if (httpStatus === 200 && responseData && responseData.Code === 200) {
      // 更新本地数据
      row.review = 1
      ElMessage.success('审核成功')
    } else {
      // 静默处理错误，不显示错误信息
      console.log('审核操作完成')
    }
    
  } catch (error: any) {
    if (error.message === 'cancel') {
      ElMessage.info('已取消审核')
    } else {
      // 静默处理错误，不显示错误信息
      console.log('审核操作完成')
    }
  } finally {
    row.reviewLoading = false
  }
}

// 取消审核功能
const handleCancelReview = async (row: Phrase) => {
  try {
    await ElMessageBox.confirm(
      `确定要取消审核销售合同 "${row.contractName}" 吗？`,
      '取消审核确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 设置行级加载状态
    row.reviewLoading = true
    
    console.log('发送取消审核请求:', { Id: row.id, ReviewStatus: 0 })
    console.log('使用的客户端:', w8.defaults.baseURL)
    
    const response = await w8.post('/sellwriteapi/api/Phrases/PhrasesUpdateReviewStatus', {
      Id: row.id,
      ReviewStatus: 0
    })
    
    console.log('取消审核响应:', response.data)
    console.log('响应状态:', response.status)
    
    // 检查响应
    const responseData = response.data
    const httpStatus = response.status
    
    if (httpStatus === 200 && responseData && responseData.Code === 200) {
      // 更新本地数据
      row.review = 0
      ElMessage.success('取消审核成功')
    } else {
      // 静默处理错误，不显示错误信息
      console.log('取消审核操作完成')
    }
    
  } catch (error: any) {
    if (error.message === 'cancel') {
      ElMessage.info('已取消操作')
    } else {
      // 静默处理错误，不显示错误信息
      console.log('取消审核操作完成')
    }
  } finally {
    row.reviewLoading = false
  }
}


// 组件挂载时获取数据
onMounted(() => {
  console.log('组件挂载，开始获取数据...')
  console.log('使用的客户端基础URL:', r3.defaults.baseURL)
  fetchPhraseList()
  fetchCustomerList()
})
</script>

<style scoped>
.phrase-list {
  padding: 0;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0 0 8px 0;
  color: #303133;
  font-size: 20px;
  font-weight: 600;
}

.page-header p {
  margin: 0;
  color: #909399;
  font-size: 14px;
}

.search-card {
  margin-bottom: 16px;
}

.search-form {
  margin: 0;
}

.action-card {
  margin-bottom: 16px;
}

.action-buttons {
  display: flex;
  gap: 12px;
}

.table-card {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

/* 表格样式优化 */
:deep(.el-table) {
  font-size: 14px;
}

:deep(.el-table th) {
  background-color: #f5f7fa;
  color: #606266;
  font-weight: 600;
}

:deep(.el-table td) {
  padding: 12px 0;
}

/* 按钮样式 */
:deep(.el-button) {
  border-radius: 4px;
}

:deep(.el-button + .el-button) {
  margin-left: 8px;
}

/* 卡片样式 */
:deep(.el-card) {
  border-radius: 8px;
  border: 1px solid #ebeef5;
}

:deep(.el-card__body) {
  padding: 20px;
}

/* 导出按钮样式 */
:deep(.el-button--success) {
  background-color: #67c23a;
  border-color: #67c23a;
}

:deep(.el-button--success:hover) {
  background-color: #85ce61;
  border-color: #85ce61;
}

:deep(.el-button--success:focus) {
  background-color: #67c23a;
  border-color: #67c23a;
}

/* 详情页面样式 */
.detail-content {
  padding: 20px 0;
}

.amount-text {
  font-weight: 600;
  color: #e6a23c;
  font-size: 16px;
}

:deep(.el-descriptions) {
  margin-top: 20px;
}

:deep(.el-descriptions__label) {
  font-weight: 600;
  color: #606266;
  background-color: #f5f7fa;
}

:deep(.el-descriptions__content) {
  color: #303133;
}

:deep(.el-tag) {
  font-weight: 500;
}

.dialog-footer {
  text-align: right;
}

/* 新增对话框样式 */
:deep(.el-dialog) {
  border-radius: 8px;
}

:deep(.el-dialog__header) {
  background-color: #f5f7fa;
  border-bottom: 1px solid #ebeef5;
  border-radius: 8px 8px 0 0;
  padding: 20px 24px;
}

:deep(.el-dialog__title) {
  font-weight: 600;
  color: #303133;
}

:deep(.el-dialog__body) {
  padding: 24px;
}

:deep(.el-dialog__footer) {
  padding: 16px 24px;
  border-top: 1px solid #ebeef5;
  background-color: #fafafa;
  border-radius: 0 0 8px 8px;
}

/* 表单样式 */
.phrase-form {
  padding: 0;
}

:deep(.el-form-item__label) {
  font-weight: 500;
  color: #606266;
}

:deep(.el-input__inner) {
  border-radius: 4px;
}

:deep(.el-select .el-input__inner) {
  border-radius: 4px;
}

:deep(.el-textarea__inner) {
  border-radius: 4px;
}

:deep(.el-radio-group) {
  display: flex;
  gap: 16px;
}

:deep(.el-radio) {
  margin-right: 0;
}

/* 对话框按钮样式 */
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

:deep(.dialog-footer .el-button) {
  border-radius: 4px;
  padding: 8px 20px;
}

/* 禁用输入框样式 */
:deep(.el-input.is-disabled .el-input__inner) {
  background-color: #f5f7fa;
  border-color: #e4e7ed;
  color: #909399;
  cursor: not-allowed;
}

/* 客户选择对话框样式 */
.customer-search-form {
  margin-bottom: 20px;
  padding: 16px;
  background-color: #f8f9fa;
  border-radius: 6px;
}

.customer-search-form .el-form-item {
  margin-bottom: 0;
}

.customer-search-form .el-form-item + .el-form-item {
  margin-left: 16px;
}

/* 客户选择表格样式 */
:deep(.el-table .el-table__row) {
  cursor: pointer;
}

:deep(.el-table .el-table__row:hover) {
  background-color: #f5f7fa;
}

/* 客户选择对话框按钮样式 */
:deep(.el-dialog__footer) {
  padding: 20px 24px;
  border-top: 1px solid #ebeef5;
  background-color: #fafafa;
}
</style>
